<template>
  <div class="mapBox">
    <div id="map" v-if="mapShow"></div>
    <div class="btn">
      <div class="overBtn" v-if="lngLats.length && mapNoneClick">
        <div class="clear" @click="clearMarker()">重新绘制</div>
        <div class="confirm" @click="getAreaData()">完成绘制</div>
      </div>

      <div class="delBtn" v-if="lngLats.length && !mapNoneClick">
        <div class="clear" @click="clearMarker()">删除</div>
        <div class="revocation" @click="deleteMarker()">撤销</div>
      </div>
    </div>
    <!-- 绘制提示 -->
    <div class="notice" v-if="isDrawShow">
      {{ notice }}
    </div>
    <!-- 开始绘制按钮 -->
    <div class="drawButton" v-show="mapNoneClick && !lngLats.length" v-if="isDrawShow">
      <div class="geoIcon" @click="goBaseGeo()"><img src="../assets/address.png" alt=""></div>
      <div class="draw" @click="mapNoneClick = false,lngLats = []">开始绘制</div>
    </div>
    <div class="drawButton drawButtonFlex" v-else-if="isListMap">
      <div class="geoIcon" @click="goBaseGeo()"><img src="../assets/address.png" alt=""></div>
      <img src="../assets/list.png" alt="" @click="toList(1)"/>
    </div>
    <div class="drawButton drawButtonFlex drawButtonFlexEnd" v-else>
      <van-icon name="cross" @click.stop="toList(2)"/>
    </div>
  </div>
</template>

<script>
import * as turf from '@turf/turf'
export default {
  data () {
    return {
      map: {},
      T: '',
      handler: null, // 圈地用的
      polygonTool: null, // 控件
      polygon: null, // 面
      currentPolygon: '',
      landData: [],
      polygonDraw: null,
      marker: null, // 地图点位
      line: null, // 地图连线
      lngLats: [], // 点位坐标
      markerList: [], //  点位数组
      addressList: [], // 搜索框
      input: '',
      drawBtn: false,
      drawData: {
        // landInfo: null
      },
      geoCenter: null,
      geocode: null,
      geoColor: '#000000,#ccc',
      polygonPath: [],
      mapShow: true,
      address: null,
      mapNoneClick: true,
      isListMap: false,
      isDrawShow: false,
      setTips:
        '<div style="width:10vw;height:2vw;background: rgba(25, 181, 96);padding:0.2vw;margin:-0.4vw 5vw 1vw -5vw;border-radius: 8px;position: absolute;top: 50%;left:-50%;">点击继续绘制，双击结束绘制</div></div>', // 绘制时显示的标签
      notice: '依次打点进行绘制，闭合轮廓结束绘制' // 绘制提示
    }
  },
  props: {
    landList: {
      type: Array
    },
    baseGeo: {
      type: String
    }
  },
  watch: {
    lngLats: {
      handler (val) {
        if (this.mapNoneClick && !val.length) {
          this.notice = '依次打点进行绘制，闭合轮廓结束绘制'
          return
        }
        if (val.length === 0) {
          this.notice = '请绘制第一个点'
          return
        }
        if (val.length === 1) {
          this.notice = '请继续绘制'
          return
        }
        if (val.length === 3 && !this.mapNoneClick) {
          this.notice = '请点击第一个点完成绘制'
        }
      }
    }
  },
  mounted () {
    setTimeout(() => {
      this.load()
    }, 10)
  },
  methods: {
    // 是否添加状态
    isAdd () {
      this.isListMap = true
      this.isDrawShow = false
    },
    // 绘制
    isDraw () {
      this.isDrawShow = !this.isDrawShow
    },
    // 切换列表地图
    changeList (type) {
      this.isListMap = type
    },
    // 是否列表跳转
    toList (type) {
      this.isListMap = type !== 1
      this.$emit('toList', type)
    },
    // 面积 中心点计算
    async getAreaData () {
      if (!this.polygonPath.length || !this.polygonDraw) {
        this.$message.error('请绘制地块')
        return
      }
      const polygonList = []
      const polygonSubmit = JSON.stringify(this.polygonPath)
      this.polygonPath.map(async (item, index) => {
        polygonList.push([item.lng, item.lat])
        if (this.polygonPath.length - 1 === index) {
          polygonList.unshift([item.lng, item.lat])
        }
      })
      const polygon = turf.polygon([polygonList])
      const area = turf.area(polygon)
      const polygonCenter = turf.centroid(polygon)
      const geocoder = new this.T.Geocoder()
      await geocoder.getLocation(
        new this.T.LngLat(
          polygonCenter.geometry.coordinates[0],
          polygonCenter.geometry.coordinates[1]
        ),
        async (result) => {
          this.$emit('dataList', {
            area: parseFloat((area * 0.0015).toFixed(2)),
            polygonCenter: JSON.stringify({
              lng: polygonCenter.geometry.coordinates[0],
              lat: polygonCenter.geometry.coordinates[1]
            }),
            zoom: this.map.getZoom(),
            address: result.getAddress(),
            polygonSubmit: polygonSubmit
          })
        }
      )
      // return turf.area(polygon, { units: 'kilometers' }).toFixed(2)
    },

    load () {
      const init = new Promise((resolve, reject) => {
        if (window.T) {
          // console.log('地图初始化成功')
          resolve(window.T)
        }
      })
      init.then((T) => {
        this.T = T
        this.map = new T.Map('map')
        this.map.centerAndZoom(new T.LngLat(108.17871, 35.60372), 5)
        this.map.panTo(new T.LngLat(108.17871, 35.60372), 16)

        // 合并所有经纬度调用setViewport在地图上显示所有圈地
        if (this.geoCenter === null && this.landList?.length !== 0) {
          let MapArray = []
          for (let i = 0; i < this.landList.length; i++) {
            const geoArray = JSON.parse(this.landList[i].geoInfo)
            MapArray = [...MapArray, ...geoArray]
          }
          this.map.setViewport(MapArray)
        } else if (this.landData.length !== 0) {
          this.map.setViewport(this.landData)
        } else {
          this.map.centerAndZoom(new T.LngLat(108.17871, 35.60372), 5)
          this.map.panTo(new T.LngLat(108.17871, 35.60372), 16)
        }

        // 双重for循环遍历所有的地块数据进行渲染
        for (let j = 0; j < this.landList.length; j++) {
          const geoObj = {}
          geoObj.geoInfo = JSON.parse(this.landList[j].geoInfo) // 经纬度
          geoObj.landName = this.landList[j].landName // 地块名称
          geoObj.landArea = this.landList[j].landArea // 地块名称

          const points = []
          for (let i = 0; i < geoObj.geoInfo.length; i++) {
            points.push(
              new T.LngLat(geoObj.geoInfo[i].lng, geoObj.geoInfo[i].lat)
            )
          }
          // 创建面对象
          this.polygon = new T.Polygon(points, {
            color: '#000000',
            weight: 3,
            opacity: 0.5,
            fillColor: '#D9D9D9',
            fillOpacity: 1,
            test: `<p>名称：${geoObj.name}</p><p>面积：${geoObj.area}亩</p>`
          })
          // 添加点击事件
          this.polygon.addEventListener('click', this.getinfo)
          // 向地图上添加面
          this.map.addOverLay(this.polygon)
          // geoObj.geoCenter = JSON.parse(this.landList[j].geoCenter)
          // const label = new T.Label({
          //   text: geoObj.landName,
          //   position: new T.LngLat(geoObj.geoCenter.lng, geoObj.geoCenter.lat),
          //   offset: new T.Point(-10 * geoObj.landName.length, 0)
          // })
          // label.setBackgroundColor('#ffffff00')
          // label.setBorderColor('#ffffff00')
          // label.setFontColor('#000')
          // label.setFontSize(14)
          // // 创建地图文本对象
          // this.map.addOverLay(label)
        }

        // 添加刚绘制的面
        const points = []
        for (let i = 0; i < this.landData.length; i++) {
          points.push(new T.LngLat(this.landData[i].lng, this.landData[i].lat))
        }
        // 创建面对象
        const color = this.geoColor.split(',').map((color) => color.trim())
        this.polygon = new T.Polygon(points, {
          color: color[0], // 线
          weight: 3,
          opacity: 0.5,
          fillColor: color[1], // 面
          fillOpacity: 0.5
          // test: '<p>名称：梅林村稻田1区</p><p>面积：295亩</p>'
        })
        // 向地图上添加面
        this.map.addOverLay(this.polygon)
        // 地图图层
        const ctrl = new T.Control.MapType([
          {
            title: '卫星',
            icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellite.png',
            layer: window.TMAP_SATELLITE_MAP
          }])
        this.map.addControl(ctrl)
        this.map.addEventListener('click', this.mapClick)
      })
    },
    mapClick (e) {
      this.addMarker(e.lnglat.getLng(), e.lnglat.getLat())
    },
    // 移动到基地定位
    goBaseGeo () {
      if (this.baseGeo !== null) {
        const geo = this.baseGeo.split(',')
        console.log(geo)
        this.map.panTo(new this.T.LngLat(geo[0], geo[1]))
      }
    },
    polyLine () {
      // 清除画线
      if (this.line) {
        this.map.removeOverLay(this.line)
      }
      const points = []
      this.lngLats.forEach((item) => {
        points.push(new this.T.LngLat(item.lng, item.lat))
      })
      this.line = new this.T.Polyline(points)
      this.map.addOverLay(this.line)
    },
    // 地图删除坐标图标
    deleteMarker () {
      this.mapNoneClick = false
      if (this.polygonDraw) {
        this.polygonDraw.onRemove()
        this.polygonDraw = null
      } else {
        this.lngLats.splice(-1, 1)
        this.map.removeOverLay(this.markerList[this.markerList.length - 1])
        this.markerList.splice(-1, 1)
      }
      if (!this.markerList.length) {
        this.mapNoneClick = true
        return
      }
      this.polyLine()
    },
    // 清空所有绘制中点位
    clearMarker () {
      if (this.polygonDraw) {
        this.polygonDraw.disableEdit()
        this.polygonDraw.onRemove()
        this.polygonDraw = null
      }
      this.markerList.map((item) => {
        this.map.removeOverLay(item)
      })
      this.markerList = []
      this.lngLats = []
      this.polyLine()
      this.mapNoneClick = true
    },
    // 地图点击事件
    addMarker (getLng, getLat) {
      console.log(2222)
      if (this.mapNoneClick) {
        return
      }
      console.log(3333)
      // if (this.marker) {
      //   this.map.removeOverLay(this.marker)
      // }
      const icon = new this.T.Icon({
        iconUrl: require('@/assets/drop.png'),
        iconSize: new window.T.Point(20, 20)
        // iconAnchor: new window.T.Point(10, 56)
      })
      const point = new this.T.LngLat(getLng, getLat)
      this.marker = new this.T.Marker(point, {
        icon
      }) // 创建标注
      this.lngLats.push({
        lng: getLng,
        lat: getLat
      })
      this.markerList.push(this.marker) // 方便删除
      this.marker.addEventListener('click', this.markClick)
      this.map.addOverLay(this.marker) // 将标注添加到地图中
      this.polyLine()
    },
    // 标注点击事件
    markClick (e) {
      if (this.lngLats.length <= 1 || this.mapNoneClick) {
        return
      }
      if (
        e.lnglat.lng === this.lngLats[0].lng &&
        e.lnglat.lat === this.lngLats[0].lat
      ) {
        this.notice = '可拖拽边界点对轮廓进行调整'
        this.mapNoneClick = true // 标注点击后地图点击事件失效
        this.polygonPath = [...this.lngLats]
        this.polygonDraw = new this.T.Polygon(
          [
            ...this.lngLats,
            { lng: this.lngLats[0].lng, lat: this.lngLats[0].lat }
          ],
          {
            color: '#000000',
            weight: 3,
            opacity: 1,
            fillColor: '#D9D9D9',
            fillOpacity: 1
          }
        )
        this.polygonDraw.enableEdit()
        // 向地图上添加面
        this.map.addOverLay(this.polygonDraw)
        this.map.removeOverLay(this.line)
      }
    },
    getinfo (e) {
      const T = this.T
      const that = this
      const p = e.target
      const lnglat = new T.LngLat(p.getCenter().lng, p.getCenter().lat) // 获取点击多边形中心经纬度
      const infoWin = new T.InfoWindow() // 创建信息窗口对象
      const Content = e.target.options.test // 设置信息窗口要显示的内容，此处可使用html代码;现在显示的就是之前在polygon实例中添加的数据
      infoWin.setContent(Content) // 信息窗口加入信息
      infoWin.setOffset(new T.Point(0, -30)) // 设置信息窗口边距，第一个决定X方向，第二个决定Y方向
      infoWin.setLngLat(lnglat) // 设置信息窗口位置
      that.map.addOverLay(infoWin) // 向地图上添加信息窗口
    }
  }
}
</script>
<style lang="scss" scoped>
#map {
  width: 100vw;
  height: 100vh;
}

.mapBox {
  position: relative;
}
//提示文本
.notice {
  position: absolute;
  bottom: 15%;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  width: 252px;
  height: 24px;
  background: rgba($color: #000000, $alpha: 0.5);
  border-radius: 12px 12px 12px 12px;
  text-align: center;
  line-height: 24px;
  color: #fff;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 12px;
}
.btn {
  position: absolute;
  bottom: 5%;
  right: 50%;
  transform: translateX(50%);
  z-index: 999;
  .overBtn {
    display: flex;
    .clear {
      width: 144px;
      height: 44px;
      background: #ffffff;
      border-radius: 24px 24px 24px 24px;
      color: #19b560;
      text-align: center;
      line-height: 44px;
      margin-right: 16px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 16px;
    }
    .confirm {
      width: 144px;
      height: 44px;
      background: #19b560;
      border-radius: 24px 24px 24px 24px;
      color: #fff;
      text-align: center;
      line-height: 44px;
      margin-right: 16px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 16px;
    }
  }
  .delBtn {
    width: 161px;
    height: 36px;
    background: #ffffff;
    border-radius: 18px 18px 18px 18px;
    display: flex;
    justify-content: space-around;
    position: relative;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    line-height: 36px;
    text-align: center;
  }
  .delBtn::before {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 12px;
    background: #9ba5a2;
    border-radius: 0px 0px 0px 0px;
  }
}
::v-deep .tdt-div-icon-black {
 border: none !important;
 background: url('./../assets/drop.png');
 background-size: 100% 100%;
 width: 15px !important;
 height: 15px !important;
 margin-left: -7.5px !important;
 margin-top: -7.5px !important;
}
::v-deep.tdt-div-icon-transparent-border {
  border-radius: 50%;
}
</style>

<style lang="scss" scoped>
.cur {
  cursor: pointer;
}

.map-address {
  height: 60vh;
}

#mapDiv {
  height: 100%;
  position: relative;
}
//绘制按钮
.drawButton {
  position: fixed;
  bottom: 2%;
  left: 32px;
  // transform: translateX(-50%);
  z-index: 1000;
  display: flex;
  align-items: center;
  .geoIcon {
    margin-right: 68px;
    > img {
      width: 25px;
    }
  }
  .draw {
    width: 144px;
    height: 44px;
    background: #19b560;
    border-radius: 24px;
    text-align: center;
    line-height: 44px;
    color: #fff;
  }
}
.drawButtonFlex {
  justify-content: space-between;
  width: 100%;
  padding: 0 15px;
  left: 0;
  .geoIcon {
    margin-right: 0
  }
  > img {
    width: 60px;
  }
}
.drawButtonFlexEnd {
  justify-content: flex-end;
  color: #fff;
  font-size: 20px
}
</style>
